package com.fbt.transfer.app.driver;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import com.aliyun.emas.apm.Apm;
import com.aliyun.emas.apm.ApmOptions;
import com.aliyun.emas.apm.crash.ApmCrashAnalysisComponent;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.common.BaiduMapSDKException;
import com.baidu.navisdk.adapter.BaiduNaviManagerFactory;
import com.baidu.navisdk.adapter.IBaiduNaviManager;
import com.baidu.navisdk.adapter.struct.BNTTsInitConfig;
import com.baidu.navisdk.adapter.struct.BNaviInitConfig;
import com.fbt.transfer.app.driver.http.ApiClient;
import com.fbt.transfer.app.driver.service.FloatingWindowService;
import com.fbt.transfer.app.driver.socket.SocketManager;
import com.fbt.transfer.app.driver.util.AppContextProvider;
import com.fbt.transfer.app.driver.util.LogUtils;
import com.fbt.transfer.app.driver.util.NotificationUtils;
import com.fbt.transfer.app.driver.util.UserManager;

/**
 * 第一个启动的类，初始化一些配置
 *
 * @author tuocoo
 * @date 2025-03-22
 * @since 1.0.0
 */
public class MyApplication extends Application {

  private static final String TAG = "MyApplication";
  private static MyApplication mInstance;
  private int activityCount = 0;
  private boolean isActivityChangingConfigurations = false;
  private SocketManager socketManager = null;
  private boolean isAppInBackground = false;

  public static Context getApplication() {
    return mInstance;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    mInstance = this;
    AppContextProvider.initialize(this);
    NotificationUtils.init(this);
    
    // 初始化百度地图SDK
    SDKInitializer.setAgreePrivacy(this, true);
    SDKInitializer.initialize(this);
    Apm.preStart(
        new ApmOptions.Builder()
            // 必须配置application
            .setApplication(this)
            // 必须配置EMAS的appKey
            .setAppKey("335544900")
            // 必须配置EMAS的appSecret
            .setAppSecret("124040fa95bb4463ba00516d160baba1")
            .setRsaPublicKey(
                "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCUsxKoakdwuB0Cdqxk7iGXkMMUxE3A98/M844Q9hLAq6jqENzAq5LUXkLp+MypX7soA650lWpoMkbS8drk01w8UrNdGswFUgRarQOVTcn+Ew11IrDT58I/V9lkU/RMIcxtlM02xHpSEDAYb8TeWQ6xNx0WHZphBHQu6pUiHNe5kwIDAQAB")
            // 必须配置，否则不会打开崩溃分析功能
            .addComponent(ApmCrashAnalysisComponent.class)
            .build());
    Apm.start();
    Apm.setUserId(UserManager.getInstance(this).getUserId());
    Apm.setUserNick(UserManager.getInstance(this).getUsername());
    socketManager = SocketManager.getInstance(this);
    registerActivityLifecycleCallbacks(
        new ActivityLifecycleCallbacks() {
          @Override
          public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            Log.d(TAG, "Activity created: " + activity.getClass().getSimpleName());
          }

          @Override
          public void onActivityStarted(Activity activity) {
            activityCount++;
            Log.d(
                TAG,
                "Activity started: "
                    + activity.getClass().getSimpleName()
                    + ", count: "
                    + activityCount);

            // 如果之前没有活动，说明应用从后台恢复
            if (activityCount == 1) {
              isAppInBackground = false;
              // 停止悬浮窗服务
              stopFloatingWindowService();
              // 设置SocketManager的前台状态
              socketManager.setBackground(false);
            }
          }

          @Override
          public void onActivityResumed(Activity activity) {
            Log.d(TAG, "Activity resumed: " + activity.getClass().getSimpleName());
            isAppInBackground = false;
            // 停止悬浮窗服务
            stopFloatingWindowService();
            // 设置SocketManager的前台状态
            socketManager.setBackground(false);
          }

          @Override
          public void onActivityPaused(Activity activity) {
            Log.d(TAG, "Activity paused: " + activity.getClass().getSimpleName());
          }

          @Override
          public void onActivityStopped(Activity activity) {
            activityCount--;
            Log.d(
                TAG,
                "Activity stopped: "
                    + activity.getClass().getSimpleName()
                    + ", count: "
                    + activityCount);

            // 如果所有活动都停止了，说明应用进入后台
            if (activityCount == 0) {
              // 延迟处理后台状态，避免Activity切换时的误判
              new Handler(Looper.getMainLooper())
                  .postDelayed(
                      () -> {
                        if (activityCount == 0) {
                          handleAppBackground();
                        }
                      },
                      100);
            }
          }

          @Override
          public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}

          @Override
          public void onActivityDestroyed(Activity activity) {
            Log.d(TAG, "Activity destroyed: " + activity.getClass().getSimpleName());
          }
        });
    ApiClient.init(this);
    try {
      // 在使用 SDK 各组间之前初始化 context 信息，传入 ApplicationContext
      SDKInitializer.setAgreePrivacy(getApplicationContext(), true);
      SDKInitializer.setCoordType(CoordType.BD09LL);
      SDKInitializer.setDebugMode(true);
      LocationClient.setAgreePrivacy(true);
      SDKInitializer.initialize(getApplicationContext());
      initNavi();
    } catch (BaiduMapSDKException e) {
      LogUtils.e("BaiduMapSDK", "初始化失败", e);
    }
  }
  private void initNavi() {
    if (BaiduNaviManagerFactory.getBaiduNaviManager().isInited()) {
      return;
    }

    BNaviInitConfig config = new BNaviInitConfig.Builder()
        .naviInitListener(new IBaiduNaviManager.INaviInitListener() {
          @Override
          public void onAuthResult(int status, String msg) {
            String result;
            if (0 == status) {
              result = "key校验成功!";
            } else {
              result = "key校验失败, " + msg;
            }
            Log.e(TAG, result);
          }

          @Override
          public void initStart() {
            Log.e(TAG, "initStart");
            BaiduNaviManagerFactory.getBaiduNaviManager().enableOutLog(true);
          }

          @Override
          public void initSuccess() {
            Log.e(TAG, "initSuccess cuid = " + BaiduNaviManagerFactory.getBaiduNaviManager().getCUID());
            // 初始化tts
            initTTS();
            sendBroadcast(new Intent("com.navi.ready"));
          }

          @Override
          public void initFailed(int errCode) {
            Log.e(TAG, "initFailed = " + errCode);
          }
        })
        .build();
    BaiduNaviManagerFactory.getBaiduNaviManager().init(this, config);
  }

  private void initTTS() {
    // 使用内置TTS
    BNTTsInitConfig config = new BNTTsInitConfig.Builder()
        .context(getApplicationContext())
        .appId("119007928")
        .appKey("UFITlg5dJalmEPDljorGAdVn")
        .secretKey("kwgV3b0UNQIKXmvLf7v2m2QeAWpN1gjx")
        .authSn("530bbc74-4ef38cee-01-0866-000a-0a25-01")
        .build();
    BaiduNaviManagerFactory.getTTSManager().initTTS(config);
  }
  /**
   * 初始化SD卡路径
   * @return
   */
  private String sdcardRootPath(){
    return Environment.getExternalStorageDirectory().getAbsolutePath();
  }
  @Override
  public void onTerminate() {
    super.onTerminate();
    // 注销 ActivityLifecycleCallbacks
    unregisterActivityLifecycleCallbacks(NotificationUtils.ACTIVITY_LIFECYCLE_CALLBACKS);
  }

  private void handleAppBackground() {
    // 如果已经在后台，不需要重复处理
    if (isAppInBackground) {
      Log.d(TAG, "App already in background, skipping");
      return;
    }

    Log.d(TAG, "App entering background");
    isAppInBackground = true;

    // 检查用户是否已登录
    if (!UserManager.getInstance(this).isLoggedIn()) {
      Log.d(TAG, "User is not logged in, not starting floating window service");
      return;
    }

    // 检查悬浮窗是否启用
    if (!UserManager.getInstance(this).isFloatingWindowEnabled()) {
      Log.d(TAG, "Floating window is disabled, not starting service");
      return;
    }

    // 检查是否有悬浮窗权限
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      if (!Settings.canDrawOverlays(this)) {
        Log.d(TAG, "No overlay permission, not starting service");
        return;
      }
    }

    // 延迟启动悬浮窗服务，避免重复启动
    new Handler(Looper.getMainLooper())
        .postDelayed(
            () -> {
              try {
                // 再次检查应用是否在后台
                if (!isAppInBackground) {
                  Log.d(TAG, "App no longer in background, skipping service start");
                  return;
                }

                // 设置SocketManager的后台状态，这会触发悬浮窗服务的启动
                socketManager.setBackground(true);
              } catch (Exception e) {
                Log.e(TAG, "Error in service start delay: " + e.getMessage());
              }
            },
            100);
  }

  private void stopFloatingWindowService() {
    try {
      Intent intent = new Intent(this, FloatingWindowService.class);
      stopService(intent);
      Log.d(TAG, "Floating window service stopped");
    } catch (Exception e) {
      Log.e(TAG, "Error stopping floating window service: " + e.getMessage());
    }
  }
}
